package gnetwork

import (
	"bytes"
	"encoding/binary"
	"errors"
)

var ErrorNonstandard = errors.New("数据包异常.")
var DefaultPackSizeMax = 0x7FF
var DefaultPackHeaderFlags = 0x169

func BuildPackData(data []byte) []byte {

	l := len(data)
	if l > DefaultPackSizeMax {
		return nil
	}

	var h PackHeader
	h.Flag = int32(DefaultPackHeaderFlags)<<22 | int32(l)

	buf := bytes.NewBuffer(nil)

	binary.Write(buf, binary.LittleEndian, &h)
	wLen, err := buf.Write(data)
	if err != nil || wLen != l {
		panic("system fail.")
	}

	var cache = make([]byte, l+PackHeaderSize)

	buf.Read(cache)
	return cache
}

//ParserPackHeader 解析包头
func ParserPackHeader(content []byte) (l int, err error) {
	var clen = len(content)
	if clen >= PackHeaderSize {
		var h PackHeader
		//以网络字节序（小端）读取数据包长度
		err = binary.Read(bytes.NewBuffer(content), binary.LittleEndian, &h)
		if err != nil {
			//不应该出错，除非代码逻辑问题
			panic(err)
		}

		flag := int(h.Flag >> 22)
		iLength := int((h.Flag << 22) >> 22)

		if flag != DefaultPackHeaderFlags || iLength < 0 || iLength > DefaultPackSizeMax {
			return 0, ErrorNonstandard
		}

		return iLength, nil
	}

	return 0, nil
}
